package ge.modules.drawables;

import ge.exceptions.FunctionNonSuported;
import ge.lowlevel.SoundEngine;
import ge.modules.Module;

public class SoundModule implements Module
{

	private String sound;
	private boolean playing;
	private boolean loop;
	
	/**
	 * 	Sets volumen between 0 and 1
	 * @param volumen Volumen value
	 */
	public static void setVolumen(float volume)
	{
		try {
			SoundEngine.get().setVolume(volume);
		} catch (FunctionNonSuported e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 	Creates a new sound module
	 * @param urlSound	Relative or abosulte position of the song
	 * 
	 */
	public SoundModule(String urlSound)
	{
		sound = urlSound;
		loop = false;
		playing = false;
		try {
			SoundEngine.get().add(sound, sound); //Magia! El Id del sonido es la primera Url con la que lo construimos
		} catch (FunctionNonSuported e) {
			e.printStackTrace();
		}	
	}
	/**
	 * 	This function is implemented in order to avoid the incompatibility format of the sound file
	 * 	in different formats. If the SoundEngine you are using is allow to difference what format
	 * 	has to be played, with this function you'll be able to show him the different options.
	 * 
	 * 	In other words: Use that function to subscribe different formats of the same sound.
	 * @param othersUrl
	 */
	public void add(String othersUrl)
	{
		try {
			SoundEngine.get().add(sound, othersUrl);
		} catch (FunctionNonSuported e) {
			e.printStackTrace();
		}	
	}
	@Override
	public void update() 
	{
		try {
			if(SoundEngine.get().isEnd(sound))
				playing = false;
			
			// Loop control
			if(loop && !playing)
			{
				//Log.write("Terminado ");
				play();
			}
		} catch (FunctionNonSuported e) {
			e.printStackTrace();
		}
	}

	@Override
	public void draw() 
	{
	}
	
	/**
	 * 	If it's true, the music will be played again when it has finished.
	 * @param loop Boolean value
	 */
	public void setLoop(boolean loop)
	{
		this.loop = loop;
	}
	/**
	 *  
	 * Plays the sound
	 */
	public void play()  
	{
		try {
			SoundEngine.get().play(sound);
			//Log.write(sound);
			playing = true;
		} catch (FunctionNonSuported e) {
			e.printStackTrace();
		}
	}
	/**
	 * 	You know.. it's like: "Shut up!" to the song.
	 */
	public void stop()
	{
		try {
			SoundEngine.get().stop(sound);
			playing = false;
		} catch (FunctionNonSuported e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 	Stops the song but it will remember how to continue at the same second
	 */
	public void pause()
	{
		try {
			SoundEngine.get().pause(sound);
			playing = false;
		} catch (FunctionNonSuported e) {
		
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @return True if the song is now playing
	 */
	public boolean isPlaying()
	{
		return playing;
	}
	@Override
	public void delete() {
		this.stop();
		
	}
}
